package string.leetcode_151;

public class TwoPointer {
    public String reverseWords(String s) {
        int left = 0;
        int right = s.length() - 1;
        // 双指针去掉首尾空格
        while (left < right && s.charAt(left) == ' ') {
            left++;
        }
        while (left < right && s.charAt(right) == ' ') {
            right--;
        }
        // 从后向前遍历
        int helper = right;
        StringBuilder res = new StringBuilder();
        while (helper >= left) {
            while (helper >= left && s.charAt(helper) != ' ') {
                helper--;
            }
            // 此时helper处于空格位置，将helper后面的单词收集，append是左闭右开的
            res.append(s, helper + 1, right + 1).append(" ");
            // 跳过中间的空格
            while (helper >= left && s.charAt(helper) == ' ') {
                helper--;
            }
            // 标记下一个单词的末尾
            right = helper;
        }
        // 这里要删除最后一个空格
        return res.deleteCharAt(res.length() - 1).toString();
    }
}
